import { Popover, Position, Store, Toggle } from "../../core";

import SearchPopover from "./SearchPopover";
import ShowSearchPopoverButton from "./ShowSearchPopoverButton";
import StoreProps from "./types/StoreProps";
import useDocument from "./useDocument";
import { FC, ReactElement } from "react";

export interface RenderShowSearchPopoverProps {
  onClick(): void;
}

type RenderShowSearchPopover = (
  props: RenderShowSearchPopoverProps
) => ReactElement;

export interface ShowSearchPopoverProps {
  children?: RenderShowSearchPopover;
}

const PORTAL_OFFSET = { left: 0, top: 8 };

const ShowSearchPopover: FC<{
  children?: RenderShowSearchPopover;
  store: Store<StoreProps>;
}> = ({ children, store }) => {
  const { currentDoc } = useDocument(store);
  const defaultChildren = (props: RenderShowSearchPopoverProps) => (
    <ShowSearchPopoverButton {...props} />
  );
  const render = children || defaultChildren;

  return currentDoc ? (
    <Popover
      position={Position.BottomLeft}
      target={(toggle: Toggle) =>
        render({
          onClick: toggle,
        })
      }
      content={(toggle: Toggle) => (
        <SearchPopover store={store} onToggle={toggle} />
      )}
      offset={PORTAL_OFFSET}
      closeOnClickOutside={false}
      closeOnEscape={true}
    />
  ) : (
    <></>
  );
};

export default ShowSearchPopover;
